package phoenixAAD.WifiFlashDrive;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketCreator extends Thread
{
	private final Protocol toProtocol;
	private ServerSocket serverSocket = null;
	private Socket socket = null;
	private IOException exception = null;
	private int timeout = 180000;
	
	/**
	 * Creates a socket with ACTIVE connection<br>
	 * Connects to the client that is hosting the connection <br>
	 * Call start() and join() before getting socket
	 * @param clientIp - the client's ip address
	 * @param clientListenPort - the client's listening port
	 * @throws IOException 
	 */
	public SocketCreator(Protocol toProtocol, String clientIp, int clientListenPort) throws IOException
	{
		this.toProtocol = toProtocol;
		socket = new Socket(clientIp, clientListenPort);
	}
	
	/**
	 * Creates a socket with PASSIVE connection<br>
	 * Waits for the client to connect to the specified port<br>
 	 * Call start() and join() before getting socket
	 * @param serverListenPort - the port on the server side to wait on
	 * @throws IOException 
	 */
	public SocketCreator(Protocol toProtocol, int serverListenPort) throws IOException
	{
		this.toProtocol = toProtocol;
		serverSocket = new ServerSocket(serverListenPort);
		serverSocket.setSoTimeout(timeout);
	}
	
	
	public void run()
	{
		if(serverSocket != null)
			try {
				socket = serverSocket.accept();
				serverSocket.close();
			} catch (IOException e) {
				exception = e;
			}
	}
	
	/**
	 * Gets the socket that the client connected
	 * @return the socket created
	 * @throws IOException
	 */
	public Socket getSocket() throws IOException
	{
		if(exception != null)
			throw exception;
		if(socket == null)
			throw new NullPointerException();
		return socket;
	}
}
